package com.zsh.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class UploadServlet extends HttpServlet {
    /**
     * 处理文件上传
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*System.out.println("文件传过来了");
        ServletInputStream inputStream = request.getInputStream();

        byte[] buffer = new byte[102400];
        int read = inputStream.read(buffer);
        System.out.println(new String(buffer,0,read));*/

        //1.判断数据是否是多段数据，只有多端数据才需要解析
        if(ServletFileUpload.isMultipartContent(request)){
            //2.fileItemFactory工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类ServletFileUpload
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            //解析得到每一个表单项fileitem
            try {
                List<FileItem> list = servletFileUpload.parseRequest(request);

                //循环判断表单项是文件还是普通
                for (FileItem fileItem:list) {
                    if(fileItem.isFormField()){
                        //普通项
                        System.out.println(fileItem.getFieldName());
                        //处理乱码，获取结果
                        System.out.println(fileItem.getString("UTF-8"));
                    }else{
                        //文件项
                        System.out.println(fileItem.getFieldName());
                        System.out.println(fileItem.getName());

                        fileItem.write(new File("E:\\new PC\\study\\java学习\\code\\javaweb\\09_EL_JSTL\\web\\WEB-INF\\images\\" + fileItem.getName()));


                    }
                }

            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}
